package com.xd.clap.services.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xd.clap.entity.Admin;
import com.xd.clap.entity.Advise;
import com.xd.clap.entity.FirstAddress;
import com.xd.clap.entity.SecondAddress;
import com.xd.clap.entity.request.AddressParam;
import com.xd.clap.entity.request.MapDetailParam;
import com.xd.clap.entity.request.MapParam;
import com.xd.clap.entity.request.PageParam;
import com.xd.clap.entity.response.*;
import com.xd.clap.mapper.AdminMapper;
import com.xd.clap.mapper.AdviseMapper;
import com.xd.clap.mapper.FirstAddressMapper;
import com.xd.clap.mapper.SecondAddressMapper;
import com.xd.clap.services.FirstAddressService;
import com.xd.clap.services.SecondAddressService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@Service
public class SecondAddressServiceImpl implements SecondAddressService {
    @Resource
    private AdminMapper am;

    @Resource
    private FirstAddressMapper fam;

    @Resource
    private SecondAddressMapper sam;

    @Resource
    private SecondAddressService sas;

    @Resource
    private FirstAddressService fas;

    @Resource
    private AdviseMapper aem;

    @Resource
    private AdminMapper anm;

    @Override
    public Result getSecondAddressListByFid(Integer id) {
        return Result.success(sas.selectSecondAddressList(id), "查询成功");
    }

    @Override
    public Result getSecondAddressList(List<String> addressList) {
        return Result.success(sas.selectSecondAddressList(addressList), "查询成功");
    }

    @Override
    public List<SecondAddress> selectSecondAddressList(Integer id) {
        LambdaQueryWrapper<SecondAddress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SecondAddress::getFid, id);
        return sam.selectList(queryWrapper);
    }

    @Override
    public List<SecondAddress> selectSecondAddressList(List<String> addressList) {
        List<SecondAddress> secondAddressList = new ArrayList<>();
        for (String address : addressList) {
            LambdaQueryWrapper<SecondAddress> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SecondAddress::getAddress, address);
            secondAddressList.add(sam.selectOne(queryWrapper));
        }
        return secondAddressList;
    }

    @Override
    public Result getMapIcon(MapParam mapDetailParam) {
        List<SecondAddress> secondAddressList;
        List<String> addressList = mapDetailParam.getAddressList();
        if (addressList != null && addressList.size() > 0) {
            secondAddressList = sas.selectSecondAddressList(addressList);
        } else {
            LambdaQueryWrapper<SecondAddress> queryWrapper = new LambdaQueryWrapper<>();
            secondAddressList = sam.selectList(queryWrapper);
        }
        List<MarkersResult> markersList = new ArrayList<>();
        String greenIcon = mapDetailParam.getGreenIcon();
        String redIcon = mapDetailParam.getRedIcon();
        String yellowIcon = mapDetailParam.getYellowIcon();
        for (SecondAddress secondAddress : secondAddressList) {
            String address = secondAddress.getAddress();
            MarkersResult markers = new MarkersResult();
            //设置ID
            markers.setId(secondAddress.getId());
            //将二级辖区设置为标题
            markers.setTitle(address);
            //设置经度
            markers.setLatitude(secondAddress.getLatitude());
            //设置纬度
            markers.setLongitude(secondAddress.getLongitude());
            //默认设置为绿色icon
            markers.setIconPath(greenIcon);
            //当待审核数量大于零设置为黄色icon
            LambdaQueryWrapper<Advise> adviseWrapper = new LambdaQueryWrapper<>();
            adviseWrapper.eq(Advise::getSecondAddress, address).eq(Advise::getStateCode, 3);
            if (aem.selectCount(adviseWrapper) > 0) {
                markers.setIconPath(yellowIcon);
            }
            //当待待处理数量大于零设置为红色icon
            adviseWrapper = new LambdaQueryWrapper<>();
            adviseWrapper.eq(Advise::getSecondAddress, address).ge(Advise::getStateCode, 1).le(Advise::getStateCode, 2);
            if (aem.selectCount(adviseWrapper) > 0) {
                markers.setIconPath(redIcon);
            }
            markersList.add(markers);
        }
        return Result.success(markersList, "查询成功");
    }

    @Override
    public Result getAddressInfo(Integer id) {
        SecondAddress secondAddress = sam.selectById(id);
        FirstAddress firstAddress = fam.selectById(secondAddress.getFid());
        AddressResult addressInfo = new AddressResult();
        //设置一级辖区
        addressInfo.setFirstAddress(firstAddress.getAddress());
        //设置一级辖区
        addressInfo.setSecondAddress(secondAddress.getAddress());
        LambdaQueryWrapper<Admin> adminWrapper = new LambdaQueryWrapper<>();
        adminWrapper.eq(Admin::getAddress, secondAddress.getAddress());
        Admin admin = anm.selectOne(adminWrapper);
        //设置管理员姓名
        addressInfo.setName(admin.getName());
        //设置管理员手机号
        addressInfo.setPhone(admin.getPhone());
        LambdaQueryWrapper<Advise> adviseWrapper = new LambdaQueryWrapper<>();
        adviseWrapper.eq(Advise::getSecondAddress, secondAddress.getAddress());
        //设置建议总数
        addressInfo.setTotal(aem.selectCount(adviseWrapper));
        adviseWrapper = new LambdaQueryWrapper<>();
        adviseWrapper.eq(Advise::getSecondAddress, secondAddress.getAddress()).ge(Advise::getStateCode, 0).le(Advise::getStateCode, 3);
        //设置未处理总数
        addressInfo.setUntreatedNum(aem.selectCount(adviseWrapper));
        adviseWrapper = new LambdaQueryWrapper<>();
        adviseWrapper.eq(Advise::getSecondAddress, secondAddress.getAddress()).ge(Advise::getStateCode, 4).le(Advise::getStateCode, 5);
        //设置已处理总数
        addressInfo.setAccomplishNum(aem.selectCount(adviseWrapper));
        return Result.success(addressInfo, "查询成功");
    }

    @Override
    public Result getAddressPage(PageParam pageParam) {
        String msg = pageParam.getMessage();
        List<FirstAddress> firstAddressList = fas.selectFirstAddressList(msg);
        List<SecondAddress> secondAddressList = new ArrayList<>();
        if (firstAddressList.size() > 0) {
            for (FirstAddress firstAddress : firstAddressList) {
                int fid = firstAddress.getId();
                secondAddressList.addAll(sas.selectSecondAddressList(fid));
            }
        } else {
            LambdaQueryWrapper<SecondAddress> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(SecondAddress::getAddress, msg);
            secondAddressList = sam.selectList(queryWrapper);
        }
        IPage<Admin> iPage = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("authority", "213261619");

        if (secondAddressList.size() > 0) {
            for (SecondAddress secondAddress : secondAddressList) {
                queryWrapper.eq("address", secondAddress.getAddress()).or();
            }
        } else {
            queryWrapper.and(wq -> wq.like("name", msg).or().like("phone", msg));
        }

        IPage<Admin> address = am.selectPage(iPage, queryWrapper);
        IPage<AddressPageResult> aPage = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        List<AddressPageResult> addressPageResultList = new ArrayList<>();
        for (Admin admin : address.getRecords()) {
            AddressPageResult addressPageResult = new AddressPageResult();
            addressPageResult.setId(admin.getId());
            addressPageResult.setPhone(admin.getPhone());
            addressPageResult.setName(admin.getName());
            addressPageResult.setAddress(admin.getAddress());
            LambdaQueryWrapper<SecondAddress> sWrapper = new LambdaQueryWrapper<>();
            sWrapper.eq(SecondAddress::getAddress, admin.getAddress());
            SecondAddress secondAddress = sam.selectOne(sWrapper);
            addressPageResult.setLatitude(secondAddress.getLatitude());
            addressPageResult.setLongitude(secondAddress.getLongitude());
            addressPageResult.setFid(secondAddress.getFid());
            addressPageResult.setSid(secondAddress.getId());
            FirstAddress firstAddress = fam.selectById(secondAddress.getFid());
            addressPageResult.setFirstAddress(firstAddress.getAddress());
            addressPageResultList.add(addressPageResult);
        }
        aPage.setTotal(address.getTotal());
        aPage.setRecords(addressPageResultList);
        return Result.success(aPage, "加载成功!");
    }

    @Override
    public Result delAddress(Integer id, Integer sid) {
        int del = am.deleteById(id);
        int sDel = sam.deleteById(sid);
        if (del > 0 && sDel > 0) {
            return Result.success(del + sDel, "删除成功");
        }
        return Result.fail(del + sDel, "删除失败");
    }

    @Override
    public Result updateAddress(AddressParam addressParam) {
        if (addressParam.getId() != null) {
            addressParam.setAuthority("213261619");
            int update = am.updateById(addressParam);
            SecondAddress secondAddress = new SecondAddress();
            secondAddress.setId(addressParam.getSid());
            secondAddress.setAddress(addressParam.getAddress());
            secondAddress.setFid(addressParam.getFid());
            secondAddress.setLatitude(addressParam.getLatitude());
            secondAddress.setLongitude(addressParam.getLongitude());
            int sUpdate = sam.updateById(secondAddress);
            if (sUpdate > 0 && update > 0) {
                return Result.success(update, "修改成功");
            }
            return Result.fail(update + sUpdate, "修改失败");
        } else {
            addressParam.setAuthority("213261619");
            int insert = am.insert(addressParam);
            SecondAddress secondAddress = new SecondAddress();
            secondAddress.setAddress(addressParam.getAddress());
            secondAddress.setFid(addressParam.getFid());
            secondAddress.setLatitude(addressParam.getLatitude());
            secondAddress.setLongitude(addressParam.getLongitude());
            int sInsert = sam.insert(secondAddress);
            if (sInsert > 0 && insert > 0) {
                return Result.success(insert + sInsert, "修改成功");
            }
            return Result.fail(insert + sInsert, "修改失败");
        }
    }
    @Override
    public Result getAdviseMapIcon(String greenIcon) {
        LambdaQueryWrapper<Advise> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Advise::getStateCode,1);
        List<Advise> advises = aem.selectList(queryWrapper);
        List<AdviseMapResult> adviseMapResults = advises
                .stream()
                .filter(advise -> {
                    String longitude = advise.getLongitude();
                    String latitude = advise.getLatitude();
                    return StringUtils.hasText(longitude) && StringUtils.hasText(latitude);
                }).map(advise -> {
                    AdviseMapResult adviseMapResult = new AdviseMapResult();
                    BeanUtil.copyProperties(advise, adviseMapResult);
                    adviseMapResult.setIconPath(greenIcon);
                    adviseMapResult.setTitle(advise.getLocation());
                    return adviseMapResult;
                }).collect(Collectors.toList());
        return Result.success(adviseMapResults, "查询成功");
    }

    @Override
    public Result getDetailMapIcon(MapDetailParam mapDetailParam) {
        List<SecondAddress> secondAddressList;
        List<String> addressList = Optional.ofNullable(mapDetailParam.getAddressList()).orElse(Collections.emptyList());
        if (!addressList.isEmpty()) {
            secondAddressList = sas.selectSecondAddressList(addressList);
        } else {
            LambdaQueryWrapper<SecondAddress> queryWrapper = new LambdaQueryWrapper<>();
            secondAddressList = sam.selectList(queryWrapper);
        }
        List<MarkersResult> markersList = new ArrayList<>();
        // 绿色图标
        String greenIcon = mapDetailParam.getGreenIcon();

        secondAddressList.forEach(secondAddress -> {
            String address = secondAddress.getAddress();
            MarkersResult markers = new MarkersResult();
            //设置ID
            markers.setId(secondAddress.getId());
            //将二级辖区设置为标题
            markers.setTitle(address);
            //设置经度
            markers.setLatitude(secondAddress.getLatitude());
            //设置纬度
            markers.setLongitude(secondAddress.getLongitude());
            //默认设置为绿色icon
            markers.setIconPath(greenIcon);
            markersList.add(markers);
        });
        return Result.success(markersList, "查询成功");
    }


}
